<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 问答管理</title>
    <!-- 引入 Element UI 样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入 Vue -->
    <script src="js/vue@2.js"></script>
    <!-- 引入 Element UI 组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- 引入 ECharts -->
    <script src="js/echarts.min.js"></script>
    <!-- 引入WangEditor -->
    <script src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"></script>
    <script src="js/axios.min.js"></script>
    <script src="js/data.js"></script>
    <style>
        .app-container {
            display: flex;
            height: 100vh;
        }

        .app-aside {
            background: #2d3a4b;
            padding: 0;
            height: 100vh;
            color: white;
        }

        .app-menu {
            height: 100%;
        }

        .app-header {
            background: #409EFF;
            color: white;
            text-align: center;
            line-height: 60px;
            height: 60px;
        }

        .app-main {
            padding: 20px;
            overflow: auto;
        }

        .el-table .is-reply-1 {
            background-color: #f0f9eb;
        }

        .el-table .is-reply-0 {
            background-color: #fef0f0;
        }

        .charts-container {
            display: flex;
            margin-top: 20px;
        }

        #line-chart, #pie-chart {
            width: 50%;
            height: 400px;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <!-- 左侧导航栏 -->
    <el-aside width="200px" class="app-aside">
        <el-menu class="app-menu" :default-openeds="['1']">
            <el-submenu index="1">
                <template slot="title">
                    <i class="el-icon-menu"></i>
                    <span>菜单</span>
                </template>

                <el-menu-item index="1-1" @click="navigateTo('Admin_index.html')">
                    <i class="el-icon-s-data"></i>仪表盘
                </el-menu-item>
                <el-menu-item index="1-2" @click="navigateTo('Admin_user.html')">
                    <i class="el-icon-user"></i>用户管理
                </el-menu-item>
                <el-menu-item index="1-3" @click="navigateTo('settings.html')">
                    <i class="el-icon-setting"></i>设置
                </el-menu-item>
                <el-menu-item index="1-4" @click="navigateTo('Admin_wenda.html')">
                    <i class="el-icon-question"></i>问答管理
                </el-menu-item>
                <el-menu-item index="1-5" @click="navigateTo('Admin_gonggao.html')">
                    <i class="el-icon-message"></i>公告管理
                </el-menu-item>
                <el-menu-item index="1-6" @click="navigateTo('Admin_gouwuche.html')">
                    <i class="el-icon-shopping-cart-full"></i>购物车管理
                </el-menu-item>

            </el-submenu>
        </el-menu>
    </el-aside>

    <!-- 右侧操作区域 -->
    <el-container>
        <el-header class="app-header">问答管理</el-header>
        <el-main class="app-main">


            <el-card class="box-card" style="margin-bottom: 20px;">

                <!-- 折线图和饼图 -->
                <div class="charts-container">
                    <div id="line-chart"></div>
                    <div id="pie-chart"></div>
                </div>
            </el-card>


            <!-- 富文本编辑器 -->
            <el-dialog :visible.sync="showDialog" :title="question_replying" width="60%" :close-on-click-modal="false">
                <!--//用户添加问答-->
                <el-form ref="editForm" label-width="600px">
                    <el-form-item :label="`请给用户： ${selectUser} 的问题质量进行评分：`">
                        <el-rate v-model="quality" :max="5"></el-rate>
                    </el-form-item>
                </el-form>


                <div id="editor" style="height: 500px;"></div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveContent">保存</el-button>
                </span>
            </el-dialog>


            <!-- 表格数据 -->
            <el-card class="box-card">
                <!-- 搜索功能模块 -->
                <!--                <div slot="header" class="clearfix">-->
                <!--                    <span>搜索问题</span>-->
                <!--                </div>-->
                <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                    <el-form-item label="问题">
                        <el-input v-model="searchForm.question" placeholder="输入问题关键字"></el-input>
                    </el-form-item>
                    <el-form-item label="用户">
                        <el-input v-model="searchForm.user" placeholder="输入用户关键字"></el-input>
                    </el-form-item>
                    <el-form-item label="是否回复">
                        <el-select v-model="isreply" placeholder="选择状态">
                            <el-option label="全部" value="all"></el-option>
                            <el-option label="已回复" value="reply"></el-option>
                            <el-option label="未回复" value="noreply"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>

                <div slot="header" class="clearfix">
                    <span>问答列表</span>
                </div>
                <el-table :data="wendaData" style="width: 100%;" stripe border :row-class-name="tableRowClassName"
                          height="400" :header-cell-styles="headerCellStyles" :header-row-style="headerRowStyle"
                          v-loading="loading">
                    <el-table-column prop="id" label="ID" width="50"></el-table-column>
                    <el-table-column prop="question" label="问题"></el-table-column>
                    <el-table-column prop="answer" label="答案">
                        <template v-slot="scope">
                            {{ scope.row.answer.length > 10 ? scope.row.answer.substring(0, 10) + '...' :
                            scope.row.answer }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="user" label="用户"></el-table-column>
                    <el-table-column prop="isreply" label="是否回复" width="100">
                        <template slot-scope="scope">
                            <el-tag :type="scope.row.isreply === 1 ? 'success' : 'danger'">
                                {{ scope.row.isreply === 1 ? '已回复' : '未回复' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="create_time" label="创建时间" width="180">

                        <template v-slot="scope">
                            {{ WenDaformatDate( scope.row.create_time) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="replytime" label="回复时间" width="180">
                        <template v-slot="scope">
                            {{ WenDaformatDate( scope.row.replytime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="quality" label="质量" width="100"></el-table-column>
                    <!-- <el-table-column prop="questiondetail" label="问题详情" width="20"></el-table-column>-->
                    <el-table-column label="操作" width="250">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.isreply === 0" type="danger" icon="el-icon-close" size="mini"
                                       @click="handleReject(scope.row)">
                                不受理
                            </el-button>
                            <el-button v-if="scope.row.isreply === 0" type="primary" icon="el-icon-edit" size="mini"
                                       @click="handleReply(scope.row)">
                                回复
                            </el-button>

                            <el-button v-if="scope.row.isreply === 1" type="danger" icon="el-icon-close" size="mini"
                                       @click="deleteTheWenDa(scope.row)">
                                删除此问答
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>


                <el-pagination
                        background
                        @current-change="handleCurrentChange"
                        layout="prev, pager, next"
                        :current-page="currentpage"
                        :page-size="pagesize"
                        :total="totalGongGaoNum">
                </el-pagination>
            </el-card>


        <!--    <el-card class="box-card">
                <div slot="header" class="clearfix" v-html="savedContent">

                </div>
            </el-card>-->

        </el-main>
    </el-container>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                showDialog: false,
                savedContent: '', // 存储保存后的HTML内容
                savedPlainText: '', // 存储保存后的纯文本内容
                selectUser: '', // 选中的用户

                //页面显示数据
                pagesize: 4,
                // 公告总数
                totalGongGaoNum: 0,
                //当前页
                currentpage: 1,
                gettype: "all",// “all”.全部   "reply".已回复  "noreply".未回复
                isreply: '',
                searchForm: {
                    showDialog: false,
                    question: '',
                    user: '',

                },
                wendaData: [],
                loading: false,
                question_replying: null,
                id_replying: null,
                quality: 0,
                isreplyWenda_list:[],
                noreplyWenda_list:[]
            }
        },
        created() {
            //检查是否已经登录
            axios.post(urlluodeng + '/admin/GetLoginUserInfo').then(res => {
                if (res.data.result) {
                    this.$message.success('欢迎回来，' + res.data.adminUser.username + '！');
                    // 获取数据
                    this.getGongGaoData(this.currentpage, this.pagesize, this.gettype);
                    this.getWenDaDataTotalNum();
                    this.getGenderData();

                } else {
                    //用户未登录
                    this.$message.error('401 未授权，请先登录');
                    setTimeout(() => {
                        window.location.href = 'Admin_login.html';
                    }, 500)
                }
            }).catch(err => {
                console.log(err);
                this.$message.error('网络错误，请稍后再试！');
                setTimeout(() => {
                    window.location.href = 'Admin_login.html';
                }, 500)
            });
        },
        watch: {
            showDialog(newVal) {
                if (newVal) {
                    this.$nextTick(() => {
                        // 在弹窗打开时初始化WangEditor
                        this.initEditor();
                    });
                } else {
                    // 在弹窗关闭时，销毁编辑器
                    this.destroyEditor();
                }
            },
            isreply(newVal) {
                console.log('isreply:', newVal);
                this.getGongGaoData(this.currentpage, this.pagesize, newVal);
            },

        },
        methods: {
            getGenderData() {
                //用户信息加载完成后，加载问答数据
                axios.get(urlluodeng + '/wenda/getNotReplyAndReplyWenda').then((response) => {
                    if (response.data.result) {

                        this.isreplyWenda_list = response.data.data.data.isReply;
                        this.noreplyWenda_list = response.data.data.data.notReply;
                        this.value1 = this.isreplyWenda_list.length + this.noreplyWenda_list.length;
                        console.log("问答数据加载完成");
                        console.log(response.data.data);
                        console.log(this.isreplyWenda_list);
                        console.log(this.noreplyWenda_list);
                        this.initPieChart();
                        this.initLineChart();
                    } else {
                        alert(response.data.msg);
                    }
                }).catch((error) => {
                    console.log(error);
                    layer.msg('网络链接失败，请稍后再试！', {icon: 2, time: 2000, btn: ['确定']});
                });
            },
            WenDaformatDate(isoString) {
                const date = new Date(isoString);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth() 返回值为 0-11
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}`;
            },

            /*获取问答数据*/
            getGongGaoData(pagenum, pagesize, gettype) {
                axios.get(`${urlluodeng}/wenda/getWendaByPage?pagenum=${pagenum}&pagesize=${pagesize}&gettype=${gettype}`).then(res => {
                    if (res.data.result) {
                        this.wendaData = res.data.data;
                    } else {
                        this.$message.error('获取问答数据失败！');
                    }
                }).catch(err => {
                    console.log(err);
                    this.$message.error('网络错误，请稍后再试！');
                });
            },
            getWenDaDataTotalNum() {
                axios.get(`${urlluodeng}/wenda/getWendaTotalNum`).then(res => {
                    if (res.data.result) {
                        this.totalGongGaoNum = res.data.data;
                    } else {
                        this.$message.error('获取问答总数失败！');
                    }
                }).catch(err => {
                    console.log(err);
                    this.$message.error('网络错误，请稍后再试！');
                });
            },
            initEditor() {
                this.editor = new window.wangEditor('#editor');
                this.editor.config.height = 200; // 设置编辑器高度
                this.editor.config.onchange = (html) => {
                    this.editorContent = html;
                };
                this.editor.create();
            },
            destroyEditor() {
                if (this.editor) {
                    this.editor.destroy();
                    this.editor = null;
                }
            },
            //----------------------------以下为业务逻辑----------

            navigateTo(page) {
                window.location.href = page; // 使用参数指定跳转页面路径
            },
            tableRowClassName({row}) {
                return row.isreply === 1 ? 'is-reply-1' : 'is-reply-0';
            },
            deleteTheWenDa(row){
                this.$confirm(`确认删除用户: ${row.user} 的问题吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let deleteForm = new FormData();
                    deleteForm.append('id', row.id);
                    axios.post(`${urlluodeng}/wenda/deleteWenda`, deleteForm).then(res => {
                        if (res.data.result) {
                            this.getGongGaoData(this.currentpage, this.pagesize, this.isreply);
                            this.getWenDaDataTotalNum();
                            this.$message.success('删除成功！');
                        } else {
                            this.$message.error('删除失败！');
                        }
                    }).catch(err => {
                        console.log(err);
                        this.$message.error('网络错误，请稍后再试！');
                    });
                }).catch(() => {
                    //取消不受理
                    this.$message.info('已取消删除操作');
                });
            },
            handleReject(row) {
                console.log('不受理:', row);
                this.$confirm(`确认不受理用户: ${row.user} 的问题吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let deleteForm = new FormData();
                    deleteForm.append('id', row.id);
                    axios.post(`${urlluodeng}/wenda/deleteWenda`, deleteForm).then(res => {
                        if (res.data.result) {
                            this.getGongGaoData(this.currentpage, this.pagesize, this.isreply);
                            this.getWenDaDataTotalNum();
                            this.$message.success('不受理成功！');
                        } else {
                            this.$message.error('不受理失败！');
                        }
                    }).catch(err => {
                        console.log(err);
                        this.$message.error('网络错误，请稍后再试！');
                    });
                }).catch(() => {
                    //取消不受理
                    this.$message.info('已取消不受理操作');
                });
            },
            handleReply(row) {
                console.log('回复:', row);
                this.question_replying = row.question; // 记录当前正在回复的问题
                this.selectUser = row.user; // 记录当前问题的用户
                this.id_replying = row.id; // 记录当前问题的ID
                this.showDialog = true; // 打开弹窗
            },
            saveContent() {
                this.savedContent = this.editorContent; // 保存编辑内容
                this.savedPlainText = this.getPlainText(this.editorContent); // 获取纯文本内容
                console.log(this.savedContent); // 可选: 打印HTML内容
                console.log(this.savedPlainText); // 可选: 打印纯文本内容
                let data = new FormData();
                data.append('answer', this.savedPlainText);
                data.append('answer_html', this.savedContent)
                data.append('id', this.id_replying);
                data.append('quality', this.quality);

                axios.post(`${urlluodeng}/wenda/replyWenda`, data).then(res => {
                    if (res.data.result) {
                        this.getGongGaoData(this.currentpage, this.pagesize, this.isreply);
                        this.showDialog = false; // 关闭弹窗
                    } else {
                        this.$message.error('保存失败！');
                    }
                }).catch(err => {
                    console.log(err);
                    this.$message.error('网络错误，请稍后再试！');
                });
            },
            getPlainText(html) {
                // 创建一个临时的DOM元素，用于提取纯文本内容
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = html;
                return tempDiv.innerText || tempDiv.textContent; // 获取纯文本
            },
            handleSearch() {
                console.log('搜索:', this.searchForm);
            },
            handleReset() {
                this.searchForm = {
                    question: '',
                    user: '',
                };
                this.isreply = 'all';
            },
            handleCurrentChange(currentPage) {
                // 切换页码时，重新获取数据
                this.currentpage = currentPage;
                this.getGongGaoData(currentPage, this.pagesize, this.isreply);
            },
            generateDateRange() {
                const dateList = [];
                const now = new Date();
                const year = now.getFullYear();
                const month = now.getMonth();
                const lastDay = new Date(year, month + 1, 0).getDate();
                for (let i = 1; i <= lastDay; i++) {
                    dateList.push(`${month + 1}-${i}`);
                }
                console.log("随机日期数据：")
                console.log(dateList)
                return dateList;
            },
            generatewendaData() {
                let data= Array.from({length: this.generateDateRange().length}, () => Math.floor(Math.random() * 20) + 5);
                console.log("随机日期数据：")
                console.log(data)
                return data;
            },
            initLineChart() {
                var lineChart = echarts.init(document.getElementById('line-chart'));
                var lineOption = {
                    title: {
                        text: '本月问答量趋势',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    xAxis: {
                        type: 'category',
                        data: this.generateDateRange()
                    },
                    yAxis: {
                        type: 'value',
                        name: '问答量'
                    },
                    series: [
                        {
                            name: '问答量',
                            type: 'line',
                            data: this.generatewendaData(),
                            itemStyle: {
                                color: '#409EFF'
                            }
                        }
                    ]
                };
                lineChart.setOption(lineOption);
            },


            initPieChart() {
                var pieChart = echarts.init(document.getElementById('pie-chart'));
                var pieOption = {
                    title: {
                        text: '回复状态占比',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b} : {c} ({d}%)'
                    },
                    series: [
                        {
                            name: '回复状态',
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: [
                                {
                                    value: this.isreplyWenda_list.length,
                                    name: '已回复',
                                    itemStyle: {color: '#67C23A'}
                                },
                                {
                                    value: this.noreplyWenda_list.length,
                                    name: '未回复',
                                    itemStyle: {color: '#F56C6C'}
                                }
                            ],
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                pieChart.setOption(pieOption);
            },
            headerCellStyles() {
                return {
                    backgroundColor: '#F2F6FC'
                }
            },
            headerRowStyle() {
                return {
                    backgroundColor: '#E8EAF1'
                }
            }
        },

    });
</script>
</body>
</html>
